package com.ambercrm.business;

import android.Manifest;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.ambercrm.R;
import com.ambercrm.base.BaseTitleActivity;
import com.ambercrm.base.MyApplication;
import com.ambercrm.beans.CommonClass;
import com.ambercrm.business.bean.EmpIeeUserInfo;
import com.ambercrm.business.bean.UploadImageBean;
import com.ambercrm.common.Common;
import com.ambercrm.constant.Constant;
import com.ambercrm.constant.UrlConstant;
import com.ambercrm.dialog_utils.BottomDialogTools;
import com.ambercrm.eventbus_event.UpdateHeaderEvent;
import com.ambercrm.http.download.FileItem;
import com.ambercrm.tools.BitmapUtil;
import com.ambercrm.tools.EmptyUtils;
import com.ambercrm.tools.LogUtils;
import com.ambercrm.tools.OnPermissionGrand;
import com.ambercrm.tools.PermissionUtils;
import com.ambercrm.tools.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.Filter;
import com.yanzhenjie.kalle.FileBinary;
import com.yanzhenjie.kalle.FormBody;
import com.yanzhenjie.kalle.Kalle;
import com.yanzhenjie.kalle.ProgressBar;
import com.yanzhenjie.kalle.simple.SimpleCallback;
import com.yanzhenjie.kalle.simple.SimpleResponse;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import de.greenrobot.event.EventBus;

public class UserInfoActivity extends BaseTitleActivity {

    private EmpIeeUserInfo empInfo;
    private RelativeLayout rlDisplayInfo;
    private TextView tvDisplayName;
    private ImageView ivUserIcon;
    private TextView tvDepartName;
    private TextView tvEmployeeName;
    private TextView tvWorkNumber;
    private TextView tvEmail;
    RelativeLayout mHeaderLayout;
    Gson mGson = new Gson();

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void initContentView(View v) {
        mTitleText.setText("个人资料");
        Bundle bundle = getBundle();
        if (bundle != null) {
            empInfo = (EmpIeeUserInfo) bundle.getSerializable("empInfo");
        }
        ivUserIcon = findViewById(R.id.iv_user_icon);
        rlDisplayInfo = findViewById(R.id.rl_display_info);
        tvDisplayName = findViewById(R.id.tv_display_name);
        tvDepartName = findViewById(R.id.tv_depart_name);
        tvEmployeeName = findViewById(R.id.tv_employee_name);
        tvWorkNumber = findViewById(R.id.tv_work_number);
        mHeaderLayout = findViewById(R.id.header_layout);
        tvEmail = findViewById(R.id.tv_email);
        initData();

        mHeaderLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<HashMap<String, String>> list = new ArrayList<>();
                HashMap<String, String> map = new HashMap<>();
                map.put("title", "拍照");
                list.add(map);
                map = new HashMap<>();
                map.put("title", "我的相册");
                list.add(map);
                map = new HashMap<>();
                map.put("title", "取消");
                list.add(map);
                BottomDialogTools.showBottomDialogText(mContext, true, list, "请选择", new BottomDialogTools.BottomDialogAdapter.OnPopupClickListener() {
                    @Override
                    public void onClick(int position, Dialog dialog) {
                        dialog.dismiss();
                        if (position == 0) {
                            PermissionUtils.requestPermission(mContext, new String[]{Manifest.permission.CAMERA}, new OnPermissionGrand() {
                                @Override
                                public void permissionGrand() { // 只拍照
                                    Album.camera(mContext) // Camera function.
                                            .image() // Take Picture.
                                            .onResult(new Action<String>() {
                                                @Override
                                                public void onAction(@NonNull String result) {
                                                    LogUtils.showLog("返回地址：" + result);
                                                    uploadFile(result);
                                                }
                                            })
                                            .onCancel(new Action<String>() {
                                                @Override
                                                public void onAction(@NonNull String result) {
                                                    LogUtils.showLog(result);
                                                }
                                            })
                                            .start();
                                }
                            });
                        }
                        else if (position == 1) {
                            PermissionUtils.requestPermission(mContext, new String[]{Manifest.permission.CAMERA}, new OnPermissionGrand() {
                                @Override
                                public void permissionGrand() {
                                    Album.image(mContext) // Image selection.
                                            .singleChoice()
                                            .camera(true)
                                            .columnCount(4)
                                            .filterMimeType(new Filter<String>() { // 过滤图片格式，只显示jpg和png的图片
                                                @Override
                                                public boolean filter(String attributes) {
                                                    return attributes.contains(".jpg") || attributes.contains(".png");
                                                }
                                            }) // 过滤文件格式
                                            .afterFilterVisibility(true) // Show the filtered files, but they are not available.
                                            .onResult(new Action<ArrayList<AlbumFile>>() {
                                                @Override
                                                public void onAction(@NonNull ArrayList<AlbumFile> result) {
                                                    uploadFile(result.get(0).getPath());
                                                }
                                            })
                                            .onCancel(new Action<String>() {
                                                @Override
                                                public void onAction(@NonNull String result) {

                                                }
                                            })
                                            .start();
                                }
                            });
                        }
                    }
                });
            }
        });
    }

    private void uploadFile(String imagePath) {
        imagePath = BitmapUtil.getSmallImage(imagePath);
        final String token = Common.getInstance().getToken();
        String url = UrlConstant.baseUploadUrl + "/upload/addFiles";
        LogUtils.showLog(url);

        FileBinary fileBinary = new FileBinary(new File(imagePath));
        fileBinary.onProgress(new ProgressBar<FileBinary>() {
            @Override
            public void progress(FileBinary origin, int progress) {
                // 单个文件进度
            }
        });

        FormBody formBody = FormBody.newBuilder()
                .param("sourceName", "bbbb")
                .param("sourceTable", "jingtian")
                .param("objectGroup", "crm")
                .param("resourceUrl", "https://filesdev.ztocwst.com/images")
                .binary("file", fileBinary)
                .build();

        formBody.onProgress(new ProgressBar<FormBody>() {
            @Override
            public void progress(FormBody origin, int progress) {
                // 整体进度
            }
        });
        Kalle.post(url)
                .body(formBody)
                .param("token", token)
                .addHeader("Authorization", token == null ? "" : (token)) // 添加请求头。
                .perform(new SimpleCallback<String>() {
                    @Override
                    public void onResponse(SimpleResponse<String, String> response) {
                        if (response.isSucceed()) {
                            // 整体上传完成的回调
                            LogUtils.showLog("上传完成：" + response.succeed());
                            CommonClass<UploadImageBean> commonClass = mGson.fromJson(response.succeed(), new TypeToken<CommonClass<UploadImageBean>>() {}.getType());

                            if (commonClass.getCode() == 105) {
                                toast(commonClass.getMsg());
                                return;
                            }

                            HashMap<String, String> map = new HashMap<>();
                            map.put("empId", empInfo.getId());
                            mHeaderUrl = commonClass.getResult().getResourceUrl()+"/"+commonClass.getResult().getResourcesId();
                            map.put("avatarUrl", mHeaderUrl);
                            httpPost(UrlConstant.UPLOAD_HEADER_URL, 0, map, true, null);
                        } else {
                            ToastUtils.showToast("上传失败：" + response.failed());
                        }
                    }
                });
    }

    String mHeaderUrl;
    @Override
    protected void onSucceed(String result, int what) {
        super.onSucceed(result, what);
        if (what == 0) {
            ivUserIcon.setVisibility(View.VISIBLE);
            rlDisplayInfo.setVisibility(View.GONE);
            empInfo.setAvatar(mHeaderUrl);
            MyApplication.getApplicationInstance().displayImg(empInfo.getAvatar() + "?token=" + Common.getInstance().getToken(), ivUserIcon);
            EventBus.getDefault().post(new UpdateHeaderEvent(mHeaderUrl));
        }
    }

    private void initData() {
        if (empInfo != null) {
            if (EmptyUtils.notEmpty(empInfo.getAvatar())) {
                ivUserIcon.setVisibility(View.VISIBLE);
                rlDisplayInfo.setVisibility(View.GONE);
                MyApplication.getApplicationInstance().displayImg(empInfo.getAvatar() + "?token=" + Common.getInstance().getToken(), ivUserIcon);
            } else {
                if (EmptyUtils.notEmpty(empInfo.getUsername())) {
                    ivUserIcon.setVisibility(View.GONE);
                    rlDisplayInfo.setVisibility(View.VISIBLE);
                    int length = empInfo.getUsername().length();
                    tvDisplayName.setText(empInfo.getUsername().substring(length-2, length));
                }
            }

            if (EmptyUtils.notEmpty(empInfo.getManageDepartNames())) {
                tvDepartName.setText(empInfo.getManageDepartNames());
            }
            if (EmptyUtils.notEmpty(empInfo.getPosition())) {
                tvEmployeeName.setText(empInfo.getPosition());
            }
            if (EmptyUtils.notEmpty(empInfo.getAccount())) {
                tvWorkNumber.setText(empInfo.getAccount());
            }
            if (EmptyUtils.notEmpty(empInfo.getEmail())) {
                tvEmail.setText(empInfo.getEmail());
            }
        }
    }
}
